use regex::Regex;

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    let re = Regex::new(r"(\w+)\((\d+)\)").unwrap();
    let caps = re.captures(num_str).unwrap();
    let source = caps.get(1).unwrap().as_str();
    let source_base = caps.get(2).unwrap().as_str().parse::<u32>().unwrap();
    std::iter::successors(
        Some(
            source
                .chars()
                .fold(0, |acc, c| acc * source_base + char_to_value(c)),
        ),
        |&n| {
            if n > 0 {
                Some(n / to_base)
            } else {
                None
            }
        },
    )
    .map(|n| value_to_char(n % to_base))
    .collect::<String>()
    .chars()
    .rev()
    .skip(1)
    .collect()
}

// 将字符转换为对应的数值
fn char_to_value(c: char) -> u32 {
    match c {
        '0'..='9' => c as u32 - '0' as u32,
        'A'..='F' => c as u32 - 'A' as u32 + 10,
        'a'..='f' => c as u32 - 'a' as u32 + 10,
        _ => panic!("Invalid character: {}", c),
    }
}

// 将数值转换为对应的字符
fn value_to_char(value: u32) -> char {
    if value < 10 {
        (value as u8 + b'0') as char
    } else {
        (value as u8 - 10 + b'a') as char
    }
}
